<script setup lang="ts">
import orderService from '@/api/modules/order/order.ts'
import SafeTopContainer from '@/components/SafeTopContainer/SafeTopContainer.vue'
import { useUcarDict } from '@/hooks/useUcarDict.ts'
import { navigateBack } from '@/utils'
import payService from "@/api/modules/pay/pay.ts";

interface OrderDetail {
  agencyFee?: number
  agentName?: string
  buyDatetime?: Date
  customerName?: string
  customerPhone?: string
  customerWechat?: string
  orderStatus?: string
  productName?: string
  queryreportUrl?: string
  returnPriceStatus?: string
  totalPrice?: number
  uploadFileUrl?: string
  vehicleBrand?: string
  vin?: string
}

const order = ref<OrderDetail>({})

const orderUuid = ref('')
const { order_status, return_price_status } = useUcarDict('order_status', 'return_price_status')
const toast = useToast()
onLoad((res) => {
  orderUuid.value = res?.orderUuid
  getOrderDetail()
})

function getOrderDetail() {
  orderService.detail(orderUuid.value).then((res) => {
    order.value = res.data
  })
}

function formatPrice(price?: number) {
  return price !== undefined ? `¥ ${price.toFixed(2)}` : '暂无'
}

function formatOrderStatus(status?: string) {
  const match = order_status.value.find(i => i.value === status)
  return match?.label ?? '未知'
}

function orderTagClass(status) {
  switch (status) {
    case 'waitVaild':
      return 'bg-orange-100 text-orange-600'
    case 'vaild':
      return 'bg-green-100 text-green-600'
    case 'invalid':
      return 'bg-red-100 text-red-600'
    default:
      return 'bg-gray-100 text-gray-600'
  }
}
// 返现状态字典
function formatReturnStatus(status?: string) {
  if (return_price_status) {
    const match = return_price_status.value.find(i => i.value === status)
    return match?.label ?? '未知'
  }
}

function handleFilePreview(url: string) {
  uni.previewImage({
    urls: [url],
  })
}

async function proceedToPay() {
  const orderData = order.value
  const amount = Number(orderData.totalPrice)
  const orderCode = orderData.orderCode
  const orderUuid = orderData.orderUuid
  try {
    const balancePayData = await payWithBalance(orderUuid, amount)
    if (balancePayData?.code === 200) {
      await updateOrderStatus({
        orderUuid,
        orderStatus: 'vaild',
        payStatus: 'paid',
      }, '支付成功')
      await handlePostPaySuccess(orderData)
    }
    else {
      const wechatPayData = await payWithWeChat(orderCode, balancePayData.data.unpaidAmount, 'U车查')
      console.log(wechatPayData)
      if (wechatPayData) {
        await updateOrderStatus({
          orderUuid,
          orderStatus: 'vaild',
          payStatus: 'paid',
        }, '支付成功')
        await handlePostPaySuccess(orderData)
      }
    }
  }
  // try {
  //   const { code: wxCode } = await uni.login({ provider: 'weixin' })
  //
  //   const payParams = {
  //     code: wxCode,
  //     orderCode: order.value.orderCode,
  //     totalFeel: Number(order.value.totalPrice),
  //     body: 'U车查',
  //   }
  //
  //   const payRes = await payService.miniAppPay(payParams)
  //   const { code, data } = payRes
  //   const paymentData = {
  //     timeStamp: data.timeStamp,
  //     nonceStr: data.nonceStr,
  //     package: data.package,
  //     signType: data.signType,
  //     paySign: data.paySign,
  //   }
  //   console.log(order.value)
  //   const orderData = order.value
  //   await uni.requestPayment({
  //     ...paymentData,
  //     success: async () => {
  //       await updateOrderStatus({
  //         orderUuid: orderData.orderUuid,
  //         orderStatus: 'vaild',
  //         payStatus: 'paid',
  //       }, '支付成功')
  //       if (orderData.orderType === 'commonOrder') {
  //         orderService.orderUseUcarQueryApi({
  //           orderUuid: orderData.orderUuid,
  //         }).then((res) => {
  //           console.log(res)
  //         })
  //       }
  //     },
  //     fail: async (err) => {
  //       console.error('支付失败', err)
  //       await updateOrderStatus({
  //         orderUuid: orderData.orderUuid,
  //         orderStatus: 'waitVaild',
  //         payStatus: 'waitPay',
  //       }, '支付失败', true)
  //     },
  //   })
  // }
  catch (err) {
    const orderData = order.value
    if (err.code === 314) {
      toast.warning('请先完成签名')
      // 可在这里引导用户跳转签名页面或弹窗
      return uni.navigateTo({
        url: `/pages/my/signature?orderCode=${orderData.orderCode}&vinNo=${orderData.vinNo}`,
      })
    }
    await updateOrderStatus({
      orderUuid: orderData.orderUuid,
      orderStatus: 'waitVaild',
      payStatus: 'waitPay',
    }, '支付失败', true)
  }
}

function handlePostPaySuccess(orderData: OrderDetail) {
  if (orderData.orderType === 'commonOrder') {
    orderService.orderUseUcarQueryApi({
      orderUuid: orderData.orderUuid,
    }).then((res) => {
      console.log(res)
    })
  }
}

async function updateOrderStatus(params, msg, isError = false) {
  try {
    await orderService.updateOrderStatus(params)
    const toastFn = isError ? toast.error : toast.success

    toastFn({
      msg,
      duration: 1000,
      closed: () => {
        getOrderDetail()
      },
    })
  }
  catch (err) {
    console.error('订单状态更新失败', err)
  }
}

function handleNavigate(id: string, url: string) {
  orderService.reportUnReadMinusOne({
    orderUuid: orderUuid.value,
  }).then((res) => {})
  if (isObsUrl(url)) {
    uni.previewImage({
      urls: [url],
    })
  }
  else {
    uni.navigateTo({
      url: `/pages/report/index?orderUuid=${id}`,
    })
  }
}

function isObsUrl(url: string): boolean {
  return typeof url === 'string' && /\.obs\./i.test(url)
}
</script>

<template>
  <div class="order-detail">
    <safe-top-container
      :padding-bottom="17"
      :show-bg-color="true"
      bg-color="#fff"
      :fixed="true"
    >
      <wd-navbar left-arrow custom-class="!bg-transparent" :bordered="false" title="订单详情" @click-left="navigateBack" />
    </safe-top-container>
    <div class="mt-22 px-4 py-2 text-sm text-gray-800 leading-relaxed">
      <div class="mb-4 rounded-xl bg-white p-5 shadow-sm">
        <div class="mb-4 flex items-center justify-between">
          <div class="flex items-center space-x-3">
            <div class="h-12 w-12 flex items-center justify-center rounded-full from-blue-500 to-indigo-600 bg-gradient-to-r">
              <image src="/static/svg/car.svg" class="h-6 w-6 text-white" />
            </div>
            <div>
              <h2 class="text-xl text-gray-900 font-bold">
                {{ order.productName || '暂无' }}
              </h2>
              <p class="text-sm text-gray-500">
                订单编号: {{ order.orderCode || '暂无' }}
              </p>
            </div>
          </div>
        </div>
        <div class="flex items-center justify-between">
          <div class="flex items-center rounded-full px-3 py-1 space-x-2" :class="orderTagClass(order.orderStatus)">
            <span class="text-sm font-medium">    {{ formatOrderStatus(order.orderStatus) || '订单状态未知' }}</span>
          </div>
          <div class="text-right">
            <div class="text-sm text-gray-500" v-if="order.buyDatetime">
              {{ formatTime(order.buyDatetime, 'YYYY-MM-DD') || '暂无' }}
            </div>
          </div>
        </div>
      </div>
      <!-- 产品信息 -->
      <div class="mb-4 rounded-xl bg-white p-4 shadow-sm">
        <div class="mb-2 text-base font-semibold">
          车辆信息
        </div>
        <div class="mb-2 flex justify-between">
          <div class="text-gray-600">
            车辆品牌
          </div>
          <div>{{ order.vehicleBrand || '暂无' }}</div>
        </div>
        <div class="flex justify-between">
          <div class="text-gray-600">
            车架号
          </div>
          <div>{{ order.vin || '暂无' }}</div>
        </div>
      </div>

      <!-- 客户信息 -->
<!--      <div class="mb-4 rounded-xl bg-white p-4 shadow-sm">-->
<!--        <div class="mb-2 text-base font-semibold">-->
<!--          客户信息-->
<!--        </div>-->
<!--        <div class="mb-2 flex justify-between">-->
<!--          <div class="text-gray-600">-->
<!--            姓名-->
<!--          </div>-->
<!--          <div>{{ order.customerName || '暂无' }}</div>-->
<!--        </div>-->
<!--        <div class="mb-2 flex justify-between">-->
<!--          <div class="text-gray-600">-->
<!--            电话-->
<!--          </div>-->
<!--          <div>{{ order.customerPhone || '暂无' }}</div>-->
<!--        </div>-->
<!--        &lt;!&ndash;        <div class="flex justify-between"> &ndash;&gt;-->
<!--        &lt;!&ndash;          <div class="text-gray-600"> &ndash;&gt;-->
<!--        &lt;!&ndash;            微信号 &ndash;&gt;-->
<!--        &lt;!&ndash;          </div> &ndash;&gt;-->
<!--        &lt;!&ndash;          <div>{{ order.customerWechat || '暂无' }}</div> &ndash;&gt;-->
<!--        &lt;!&ndash;        </div> &ndash;&gt;-->
<!--      </div>-->

      <!-- 支付信息 -->
      <div class="mb-4 rounded-xl bg-white p-4 shadow-sm">
        <div class="mb-2 text-base font-semibold">
          返现信息
        </div>
        <div class="mb-2 flex justify-between">
          <div class="text-gray-600">
            返现状态
          </div>
          <div>{{ order.returnPriceStatusDict || '暂无' }}</div>
        </div>
        <div class="flex justify-between">
          <div class="text-gray-600">
            返现金额
          </div>
          <div>{{ formatPrice(order.totalRealPrice) || '暂无' }}</div>
        </div>
      </div>

      <!-- 代理商信息 -->
      <div v-if="order.agentName" class="mb-4 rounded-xl bg-white p-4 shadow-sm">
        <div class="mb-2 text-base font-semibold">
          代理商信息
        </div>
        <div class="mb-2 flex justify-between">
          <div class="text-gray-600">
            代理商姓名
          </div>
          <div>{{ order.agentName || '暂无' }}</div>
        </div>
        <div class="flex justify-between">
          <div class="text-gray-600">
            代理费
          </div>
          <div>{{ formatPrice(order.agencyFee) }}</div>
        </div>
      </div>

      <!-- 附加信息 -->
      <div v-if="order.orderStatus !== 'invalid'" class="rounded-xl bg-white p-4 shadow-sm mb-12">
        <div class="mb-2 text-base font-semibold">
          附加文件
        </div>
        <div class="space-y-4">
          <div v-if="order.uploadFileUrl" class="flex cursor-pointer items-center rounded-lg bg-gray-50 p-3">
            <div class="h-10 w-10 flex items-center justify-center rounded-full bg-blue-100">
              <image src="/static/svg/file.svg" class="h-5 w-5" />
            </div>
            <div class="ml-3 text-gray-700">
              上传文件
            </div>
            <div class="ml-auto">
              <div
                class="text-blue-500 underline"
                @click="handleFilePreview(order.uploadFileUrl)"
              >
                点击查看
              </div>
            </div>
          </div>
          <div v-else class="mb-2 flex cursor-pointer items-center rounded-lg bg-gray-50 p-3">
            <div class="h-10 w-10 flex items-center justify-center rounded-full bg-blue-100">
              <image src="/static/svg/file.svg" class="h-5 w-5" />
            </div>
            <div class="ml-3 text-gray-600">
              上传文件
            </div>
            <div class="ml-auto">
              暂无
            </div>
          </div>

          <div v-if="order.queryreportUrl" class="flex cursor-pointer items-center rounded-lg bg-gray-50 p-3">
            <div class="h-10 w-10 flex items-center justify-center rounded-full bg-blue-100">
              <image src="/static/svg/file.svg" class="h-5 w-5" />
            </div>
            <div class="ml-3 text-gray-700">
              查询报告
            </div>
            <div class="ml-auto">
              <div
                class="text-blue-500 underline"
                @click="handleNavigate(order.orderUuid, order.queryreportUrl)"
              >
                点击查看
              </div>
            </div>
          </div>
          <div v-else class="flex cursor-pointer items-center rounded-lg bg-gray-50 p-3">
            <div class="h-10 w-10 flex items-center justify-center rounded-full bg-blue-100">
              <image src="/static/svg/file.svg" class="h-5 w-5" />
            </div>
            <div class="ml-3 text-gray-600">
              查询报告
            </div>
            <div class="ml-auto">
              暂无
            </div>
          </div>
        </div>
      </div>
    </div>
    <div
      class="shadow-t fixed bottom-0 left-0 right-0 z-50 flex items-center justify-between bg-white px-4 py-3"
    >
      <div class="text-sm text-gray-600">
        总计：<span class="text-xl text-red-500 font-bold">{{ formatPrice(order.totalRealPrice) }} 元</span>
      </div>
<!--      <wd-button-->
<!--        v-if="order.payStatus === 'waitPay'" type="primary"-->
<!--        @click="proceedToPay"-->
<!--      >-->
<!--        去支付-->
<!--      </wd-button>-->
    </div>
  </div>
</template>

<style lang="scss" scoped>
</style>
